package sktit.practice.jpaint.draw;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import sktit.practice.jpaint.canvas.Canvas;
import sktit.practice.jpaint.canvas.RectangleCanvas;
import sktit.practice.jpaint.shape.Rectangle;
import sktit.practice.jpaint.util.ShapeUtils;

public class RectangleDraw extends AbstractDraw {
	
	public RectangleDraw(Shell aShell, Display aDisplay, Color aColor, int aWidth,
			int aStyle)
	{
		super(aShell, aDisplay, aColor, aWidth, aStyle);

		mouseMoveListener = new MouseMoveListener(){

			@Override
			public void mouseMove(MouseEvent arg0) {
				if(isDrawing)
				{
					GC gc = createGC();
					gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
					gc.drawRectangle(ShapeUtils.generate(begin, temp));
					gc.setForeground(getColorBorder());
					gc.drawRectangle(ShapeUtils.generate(new Point(arg0.x, arg0.y), begin));
					canvasManager.draw();
					gc.dispose();
					temp.x = arg0.x;
					temp.y = arg0.y;
					
				}
			}
			
		};
		
		mouseListener = new MouseListener() {
			
			@Override
			public void mouseUp(MouseEvent arg0) {
				Point end = new Point(arg0.x, arg0.y);
				
				vertex.add(new Point(Math.min(begin.x, end.x), Math.min(begin.y, end.y)));
				vertex.add(new Point(Math.max(begin.x, end.x), Math.min(begin.y, end.y)));
				vertex.add(new Point(Math.max(begin.x, end.x), Math.max(begin.y, end.y)));
				vertex.add(new Point(Math.min(begin.x, end.x), Math.max(begin.y, end.y)));
				
				Canvas rectangleCanvas = new RectangleCanvas(createGC(), new Rectangle(vertex));
				canvasManager.add(rectangleCanvas);
				vertex.clear();
				isDrawing = false;
				
			}
			
			@Override
			public void mouseDown(MouseEvent arg0) {
				if (!isDrawing)
				{
					begin = new Point(arg0.x, arg0.y);
					temp = new Point(arg0.x, arg0.y);
					isDrawing = true;
				}
				
			}
			
			@Override
			public void mouseDoubleClick(MouseEvent arg0) {
				
			}
		};
	
		shell.addMouseMoveListener(mouseMoveListener);
		shell.addMouseListener(mouseListener);
	}
	
}
